package cn.hubujyjs.trainingapp.utils;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 统一返回结果
 * @param <T> 返回类型
 */
@Data
@NoArgsConstructor
public class R<T> implements Serializable {
    static final long serialVersionUID = 42L;

    public static final int SUCCESS = Constants.SUCCESS;

    public static final int FAIL = Constants.FAIL;

    private int code;

    private String msg;

    private T data;

    /**
     * 设置返回结果
     * @param data 数据
     * @param code 状态码
     * @param msg 消息
     * @return R
     * @param <T> 数据type
     */
    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> r = new R<>();
        r.setCode(code);
        r.setData(data);
        r.setMsg(msg);
        return r;
    }

    public static <T> R<T> ok() {
        return restResult(null, SUCCESS, "操作成功");
    }
    public static <T> R<T> ok(T data) {
        return restResult(data, SUCCESS, "操作成功");
    }

    public static <T> R<T> fail(String msg) {
        return restResult(null, FAIL, msg);
    }

    /**
     * 自定义消息
     * @param msg 消息
     * @return this链式调用
     */
    public R<T> msg(String msg){
        this.setMsg(msg);
        return this;
    }

    /**
     * 自定义返回状态码
     * @param code 状态码
     * @return this链式调用
     */
    public R<T> code(int code){
        this.setCode(code);
        return this;
    }
}
